package com.magic233.controller;

import com.magic233.entity.*;
import com.magic233.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * ClassName: UserController
 * Description:
 * date: 2021/5/29 20:57
 * author: zouyuan
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private CodeService codeService;

    @Autowired
    private LogsService logsService;

    @Autowired
    private WorkTypeService workTypeService;

    @Autowired
    private DeptsService deptsService;

    @Autowired
    private MessageService messageService;

    //用户注册
    @RequestMapping("/register")
    public Object register(Long id, String username, String phone, String password, String code) {
        if (id == null || username == null || phone == null || password == null || code == null || "".equals(username) || "".equals(phone) || "".equals(password) || "".equals(code)) {
            System.out.println("参数为空");
            return 2;
        }

        Users user = new Users();
        user.setId(id);
        user.setUsername(username);
        user.setPhone(phone);
        user.setPassword(password);
        user.setCode(code);
        user.setDeleted(0);

        boolean b = codeService.verifyCode(phone, code);
        if (b) {
            //验证成功
            int i = usersService.addUser(user);
            if (i == 1) {
                //注册成功
                return 1;
            } else {
                //注册失败
                return 2;
            }
        } else {
            //验证失败
            return 3;
        }
    }

    //用户登录
    @RequestMapping("/login")
    public Object login(String phone, String password) {
        System.out.println("用户登录");
        return usersService.login(phone, password);
        //status 1:登录成功，2：登录失败
    }

    //用户登出
    @RequestMapping("/logout")
    public Object logout(HttpServletRequest request, String token) {
        System.out.println("用户退出");
        Long logout = usersService.logout(token);
        return logout;
        //status 1:登录成功，2：登录失败
    }

    @RequestMapping("/bindOpenid")
    public Users bindOpenid(HttpServletRequest request, String code) {
        System.out.println("绑定openid");
        Users user = (Users) request.getAttribute("user");
        System.out.println(user);
        System.out.println(code);

        Users users = usersService.bindOpenid(user, code);

        return users;
    }

    //用户修改密码
    @RequestMapping("/changePassword")
    public Object changePassword(HttpServletRequest request, String code, String password) {
        if (code == null || password == null || "".equals(code) || "".equals(password)) {
            System.out.println("参数为空");
            return 0;
        }
        Users user = (Users) request.getAttribute("user");
        int re = usersService.changePassword(user, code, password);
        return re;
    }

    //用户重置密码
    @RequestMapping("/resetPassword")
    public Object resetPassword(String phone, String code, String password) {
        int re = usersService.resetPassword(phone, code, password);
        return re;
    }

    //用户修改手机号
    @RequestMapping("/changePhone")
    public Object changePhone(HttpServletRequest request, String code, String phone) {
        if (code == null || phone == null || "".equals(code) || "".equals(phone)) {
            System.out.println("参数为空");
            return 0;
        }
        Users user = (Users) request.getAttribute("user");
        int re = usersService.changePhone(user, code, phone);
        return re;
    }

    //用户未登录
    @RequestMapping("/noLogin")
    public Object noLogin() {
        Map map = new HashMap<>();
        map.put("status", 444);
        map.put("description", "token失效");
        return map;
    }

    //用户权限不足
    @RequestMapping("/noPermissions")
    public Object noPermissions() {
        Map map = new HashMap<>();
        map.put("status", 445);
        map.put("description", "权限不足");
        return map;
    }

    //验证id是否重复
    @RequestMapping("/verifyId")
    public Object verifyId(Long id) {
        int re = usersService.verifyId(id);
        return re;
        //1为id存在，0为id不存在
    }

    //验证手机号是否重复
    @RequestMapping("/verifyPhone")
    public Object verifyPhone(String phone) {
        int re = usersService.verifyPhone(phone);
        return re;
        //1为phone存在，0为phone不存在
    }

    //用户提交工单
    @RequestMapping("/addOrder")
    public Object addOrder(HttpServletRequest request, String reason, String address, String type, String imgsfileids1, String wxMessageOpen) {
        System.out.println("用户提交工单");
        Users user = (Users) request.getAttribute("user");
        if (reason == null || address == null || type == null || wxMessageOpen == null || "".equals(reason) || "".equals(address) || "".equals(type) || "".equals(wxMessageOpen)) {
            System.out.println("参数为空");
            return 0;
        }
        Orders order = new Orders();
        order.setReason(reason);
        order.setAddress(address);
        order.setType(type);
        order.setImgsfileids1(imgsfileids1);
        order.setWxMessageOpen(wxMessageOpen);
        int re = ordersService.addOrder(user, order);
        return re;
    }

    //用户撤销工单
    @RequestMapping("/removeOrder")
    public Object removeOrder(HttpServletRequest request, Long id) {
        System.out.println("用户撤销工单");
        if (id == null) {
            return 0;
        }

        Users user = (Users) request.getAttribute("user");
        int re = ordersService.removeOrder(user, id);
        return re;
    }

    //用户确认工单完成
    @RequestMapping("/completeOrder")
    public Object completeOrderOrder(HttpServletRequest request, Long id, String comment, Double score1, Double score2, Double score3) {
        System.out.println("用户确认维修完成");
        if (id == null || comment == null || "".equals(comment) || score1 == null || score2 == null || score3 == null) {
            System.out.println("参数为空");
            return 0;
        }

        Users user = (Users) request.getAttribute("user");
        int re = ordersService.userCompleteOrder(user, id, comment, score1, score2, score3);
        return re;
    }


    //查询维修类别
    @RequestMapping("/selectWorkType")
    public Object selectWorkType() {
        List<WorkType> workTypes = workTypeService.selectWorkType();
        return workTypes;
    }

    //查询系部
    @RequestMapping("/selectDept")
    public Object selectDept() {
        List<Depts> depts = deptsService.selectDept();
        return depts;
    }

    //查询工单
    @RequestMapping("/selectOrders")
    public Object selectOrders(HttpServletRequest request, String status, String type, Long startTime, Long endTime, Integer pageNum, Integer pageSize) {
        System.out.println("普通用户查询工单");
        Users user = (Users) request.getAttribute("user");
        Orders order = new Orders();
        order.setUid(user.getId());
        if (status == null || "".equals(status)) {
            order.setStatus("全部状态");
        } else {
            order.setStatus(status);
        }
        if (type == null || "".equals(type)) {
            order.setType("全部类别");
        } else {
            order.setType(type);
        }
        order.setSelectStartTime(startTime);
        order.setSelectEndTime(endTime);
        Map<Object, Object> map = ordersService.selectOrders(order, pageNum, pageSize);
        return map;
    }

    @RequestMapping("/uploadImg")
    public Object uploadImg(@RequestParam(value = "files") MultipartFile[] files, HttpServletRequest request) {
        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
        String dirPath = jarF.getParentFile().toString() + "/upload/";
        System.out.println("文件上传路径：" + dirPath);

        File filePath = new File(dirPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }


        System.out.println("图片数：" + files.length);


        List<String> list = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isEmpty()) {
                System.out.println("图片为空");
                continue;
            } else {
                String fileName = UUID.randomUUID() + ".png"; // 文件名
                File dest = new File(dirPath + fileName);
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                try {
                    files[i].transferTo(dest);
                    System.out.println("图片上传成功");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                list.add(fileName);
            }
        }
        return list;
    }


    @RequestMapping("/uploadImgOne")
    public Object uploadImgOne(MultipartFile file, HttpServletRequest request) {
        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
        String dirPath = jarF.getParentFile().toString() + "/upload/";
        System.out.println("文件上传路径：" + dirPath);

        File filePath = new File(dirPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }


        String fileName = UUID.randomUUID() + ".png"; // 文件名
        File dest = new File(dirPath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            System.out.println("图片上传成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileName;
    }

    @RequestMapping("/selectMessage")
    public Object selectMessage(HttpServletRequest request, String status, Integer pageNum, Integer pageSize) {
        Users user = (Users) request.getAttribute("user");
        Message message = new Message();
        message.setRecipientid(user.getId());
        message.setStatus(status);
        Map<Object, Object> messages = messageService.selectMessage(message, pageNum, pageSize);
        return messages;
    }

    @RequestMapping("/confirmRead")
    public Object confirmRead(HttpServletRequest request, Long id) {
        if (id == null) {
            return 0;
        }
        Users user = (Users) request.getAttribute("user");
        int re = messageService.updateMessageStatus(user, id);
        return re;

    }

//    @RequestMapping("/aaa")
//    public Object aaa() {
//        System.out.println("密码加密开始");
//        List<Users> users = usersService.selectAllUser();
//        for (int i = 0; i < users.size(); i++) {
//            System.out.println(i);
//            System.out.println("id: " + users.get(i).getId());
//            System.out.println("username: " + users.get(i).getUsername());
//            System.out.println("phone   : " + users.get(i).getPhone());
//            System.out.println("password: " + users.get(i).getPassword());
//            System.out.println("dept    : " + users.get(i).getDept());
//            int re = usersService.updatePasswordNoAuth(users.get(i).getId(), users.get(i).getPassword());
//            if (re == 1) {
//                System.out.println("密码加密成功");
//                System.out.println();
//                continue;
//            } else {
//                break;
//            }
//        }
//        return null;
//    }
}
